package com.yuyou.tas.lesson.service.impl;


import com.yuyou.tas.lesson.mapper.BaseTrimesterMapper;
import com.yuyou.tas.lesson.mapper.LessonClassMapper;
import com.yuyou.tas.lesson.mapper.LessonMapper;
import com.yuyou.tas.lesson.service.IBaseTermService;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseTerm;
import com.yuyou.tas.service.api.lesson.entity.BaseTrimester;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.service.api.lesson.entity.LessonClass;
import com.yuyou.tas.service.api.report.entity.ExamModel;
import com.yuyou.tas.service.api.report.service.ExamModelAPI;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.lesson.LessonBaseEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class BaseTermServiceImpl implements IBaseTermService {

    @Autowired
    private BaseTrimesterMapper mapper;

    @Autowired
    private LessonClassMapper lessonClassMapper;

    @Autowired
    private LessonMapper lessonMapper;

    @Autowired
    private ExamModelAPI examModelAPI;


    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo addTerm(String name, Integer sort, Integer isTan,Long pId, LoginRedisObj user,Long organId) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"插入成功");
        BaseTrimester bt = new BaseTrimester();
        bt.setId(Sequence.getSequence().nextId());
        bt.setName(name);
        bt.setSort(sort);
        bt.setAuthOrganizationId(organId);
        bt.setCreateUser(user.getUserId());
        bt.setCreateTime(new Date());
        bt.setIsStan(isTan);
        bt.setIsUse(LessonBaseEnums.isEnableed.enabl.getValue());
        bt.setpId(pId);
        bt.setValue(bt.getId());

        //获取最大code值
        Map<String, Object> condion = new HashMap<>();
        condion.put("organ_id",organId);
        condion.put("isUse","1");
        Long maxCode = mapper.findMaxCode(condion);
        bt.setCode(maxCode != null ? (maxCode+1)+"":"1");

        mapper.insert(bt);

        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo updateTerm(String name, Integer sort, Integer isTan,Long pId, Long id) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"更新成功");
        BaseTrimester bt = new BaseTrimester();
        bt.setId(id);
        bt.setIsStan(isTan);
        bt.setName(name);
        bt.setSort(sort);
        if (pId != null){
            bt.setpId(pId);
        }
        mapper.updateByPrimaryKeySelective(bt);

        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo delTerm(Long id) {
        //判断是否有被班级所引用
        List<LessonClass> lcs = lessonClassMapper.selectByTrimester(id);
        if(!CollectionUtils.isEmpty(lcs)){//已被班级引用
            final List<String> existList = new ArrayList<>();
            lcs.stream().limit(3).forEach(lc -> existList.add(lc.getName()));
            throw new BusinessException("无法删除，该学期已经被["+String.join(",",existList)+"]班级引用");
        }

        //判断是否被课程所引用
        List<Lesson> ls = lessonMapper.selectByTrimester(id);
        if(!CollectionUtils.isEmpty(ls)){//已被班级引用
            final List<String> existList = new ArrayList<>();
            ls.stream().limit(3).forEach(l -> existList.add(l.getName()));
            throw new BusinessException("无法删除，该学期已经被["+String.join(",",existList)+"]课程引用");
        }

        //判断是否被试卷模版引用
        List<ExamModel> examModels = examModelAPI.selectModelByTrimester(id);
        if(!CollectionUtils.isEmpty(examModels)){//已被班级引用
            final List<String> existList = new ArrayList<>();
            examModels.stream().limit(3).forEach(e -> existList.add(e.getName()));
            if(examModels.size() > 3){
                throw new BusinessException("无法删除，该学期已经被["+String.join(",",existList)+"]等"+examModels.size()+"个课程引用");
            }else{
                throw new BusinessException("无法删除，该学期已经被["+String.join(",",existList)+"]课程引用");
            }
        }

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"删除成功");
        mapper.deleteByPrimaryKey(id);

        return info;
    }

    @Override
    public ResBoolSimpleInfo<BaseTrimester> getTermByID(Long id) {
        BaseTrimester bt = mapper.selectByPrimaryKey(id);

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,null,bt);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public int findTermCount(Pagination<DtoBaseTerm> queryPgn) {
        return mapper.findTermCount(queryPgn);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public List<DtoBaseTerm> findTermPageList(Pagination<DtoBaseTerm> queryPgn) {
        return mapper.findTermPageList(queryPgn);
    }

    @Override
    public int findUserTermCount(Pagination<DtoBaseTerm> queryPgn) {
        return mapper.findUserTermCount(queryPgn);
    }

    @Override
    public List<DtoBaseTerm> findUserTermPageList(Pagination<DtoBaseTerm> queryPgn) {
        return mapper.findUserTermPageList(queryPgn);
    }

    @Override
    public BaseTrimester selectByPKandOrgan(Long id, Long authOrganizationId) {
        return mapper.selectByPKandOrgan(id, authOrganizationId);
    }

    @Override
    public BaseTrimester findById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

	@Override
	public BaseTrimester selectByCode7Organ(String code, Long authOrganizationId) {
		return mapper.selectByCode7Organ(code, authOrganizationId);
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> syncTrimester(List<BaseTrimester> list) {
		for(BaseTrimester b:list){
			BaseTrimester baseTrimester=this.selectByOrgan7OId(b.getoId(),b.getAuthOrganizationId());
			BaseTrimester up=new BaseTrimester();
			DefindBeanUtils.copyProperties(b, up);
			if(baseTrimester!=null){
				up.setId(baseTrimester.getId());
				this.updateByPrimaryKeySelective(up);
			}else{
				up.setIsStan(0);
				up.setIsUse(LessonBaseEnums.isEnableed.enabl.getValue());
			
		        //获取最大code值
		        Map<String, Object> condion = new HashMap<>();
		        condion.put("organ_id",b.getAuthOrganizationId());
		        condion.put("isUse",LessonBaseEnums.isEnableed.enabl.getValue());
                Long maxCode = mapper.findMaxCode(condion);
		        up.setCode(maxCode != null ? (maxCode+1)+"":"1");				
				this.insert(up);
			}
			
		}	
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public BaseTrimester selectByOrgan7OId(Long oId, Long authOrganizationId) {
		return mapper.selectByOrgan7OId(oId, authOrganizationId);
	}

	@Override
	@Deprecated
	public int delByOrgan7OId(Long oId, Long authOrganizationId) {
//		return mapper.delByOrgan7OId(oId, authOrganizationId);
		return 0;
	}

	@Override
	public int deleteByPrimaryKey(Long id) {
		return mapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(BaseTrimester record) {
		record.setId(Sequence.getSequence().nextId());
		record.setValue(record.getId());
		record.setCreateTime(new Date());
		return mapper.insert(record);
	}

	@Override
	public BaseTrimester selectByPrimaryKey(Long id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(BaseTrimester record) {
		return mapper.updateByPrimaryKeySelective(record);
	}

	@Override
	@Transactional(rollbackFor=Exception.class,timeout=60)
	public ResBoolSimpleInfo<String> delTrimesterByOrgan7OIds(List<Long> oIds,
			Long authOrganizationId) {
		for(Long oId:oIds){
			this.delByOrgan7OId(oId, authOrganizationId);
		}		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public List<BaseTrimester> findTrimByOran(Long authOrganizationId) {
		return mapper.findTrimByOran(authOrganizationId);
	}

    @Override
    public ResBoolSimpleInfo updateTermStatus(Long id, Integer status) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"更新成功");
        BaseTrimester t = new BaseTrimester();
        t.setId(id);
        t.setIsUse(status);
        mapper.updateByPrimaryKeySelective(t);
        return info;
    }
}